const koa = require("koa");

let router = require('koa-router')();

const bodyParser = require('koa-bodyparser');

const koaBody = require('koa-body');

const multiparty = require('koa2-multiparty');

const fs = require('fs');

const superagent =  require('superagent');
require('superagent-proxy')(superagent);

//const bodyParser = require('koa-bodyparser');

let app = new koa();

app.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
await next();
});

app.use(koaBody({
  multipart: true // 是否支持 multipart-formdate 的表单
}));

app.use(bodyParser());

// app.use(async (ctx)=>{
//     ctx.body = "你好";
// });

router.get('/',async (ctx)=>{
    ctx.body="首页"; //返回数据 相当于原生里面的res.writeHead() res.end();
}).get('/news',async (ctx)=>{
    ctx.body="新闻页面";
})

function bytesToBinary(bytes) {
 const length = bytes.length;
 let result = '';
 for (let i = 0; i < length; i++) {
  const binStr = Number(bytes[i]).toString(2)
  result += '0'.repeat(8 - binStr.length) + binStr; // 不足八位前置补0
 }
 return result.toString();
}

const PostFile =  async (aid, session_id, stream) => {

    let result = '';
    //https://www.turnitin.com/t_submit.asp?aid=115262793&session-id=da1e24a249a54f36a19e4ba7727993a6&lang=zh_hans
    let url = 'https://www.turnitin.com/t_submit.asp' + '?aid='+aid+'&session-id='+session_id+'&lang=zh_hans';
   
    let data = {
        async_request: 1,
        userID: '',
        author_first: 'li',
        author_last: 'lao',
        title: '文档',
        userfile: stream,
        db_doc: '',
        dropbox_filename: '',
        google_doc: '',
        google_auth_uri: '',
        token: '',
        submit_button: ''
    }

    try{
        result = await httpPost(url, JSON.stringify(data), 'application/x-www-form-urlencoded');
    }catch(e){
        logger(e);
    }

    logger('result', result);

    return result;

}

function streamToBuffer(stream) {  
  return new Promise((resolve, reject) => {
    let buffers = [];
    stream.on('error', reject);
    stream.on('data', (data) => buffers.push(data))
    stream.on('end', () => resolve(Buffer.concat(buffers)))
    return buffers;
  });
}

const logger = function() {
	console.log('[', (new Date()).Format("yyyy-MM-dd hh:mm:ss"), ']', ...arguments);
	//consoleLogger.log('[', (new Date()).Format("yyyy-MM-dd hh:mm:ss"), ']', ...arguments);
	return null;
}

Date.prototype.Format = function (fmt) { //author: meizz
	var o = {
		"M+": this.getMonth() + 1,                 //月份
		"d+": this.getDate(),                    //日
		"h+": this.getHours(),                   //小时
		"m+": this.getMinutes(),                 //分
		"s+": this.getSeconds(),                 //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds()             //毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

router.post('/upload', async function(ctx) {
	// console.log(ctx.request.body)
	// console.log(ctx.request.files)

	var file = ctx.request.files.abc    //传输文件的name是abc
    //console.log(file)

    var tmpath= file['path'];
    var tmparr =file['name'].split('.');
    var path = '';
    //console.log(tmpath);
    //console.log(newpath);
    var ext ='.'+tmparr[tmparr.length-1];
    var newpath = './' + parseInt(Math.random()*100) + Date.parse(new Date()).toString() + ext;

    //let bufferData = new Buffer(); 

    //console.log(newpath);
    //var stream = fs.createWriteStream(bufferData);//创建一个可写流
    //var data = fs.createReadStream(tmpath).pipe(stream);//可读流通过管道写入可写流

    var data = fs.createReadStream(tmpath);

    //logger(11);

    let buffers = await streamToBuffer(data);

    //logger('buffers', buffers);

    await PostFile('115365018', 'e33074a6f837411a9383755058bd6d54', bytesToBinary(buffers));
  // don't forget to delete all req.files when done
});

const httpPost = (url, data, contentType = null, proxy) => {
	return new Promise((resolve, reject) => {
		superagent.post(url).timeout(25000)
			.set('user-agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36')
			.set('content-type',contentType)
			.send(data)
			.end((err, res) => {
				if (err) {
					return reject(err);
				}
				resolve(res.text);
			});
	});
}


app.use(router.routes()).use(router.allowedMethods()); //建议配置：作用：可以根据ctx.status设置response响应头

app.listen(3000);